<template>
    <div class="content-box">
      <div ref="searchBox" class="search-box flex" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="130px"
        >
        <el-form-item label="号段屏蔽状态" prop="isShield">
          <el-select
            v-model="queryParams.isShield"
            clearable
            filterable
            placeholder="请选择"
            style="width: 240px; margin-right: 20px"
          >
            <el-option
              v-for="(item, index) in isShieldOption"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
         label="产品集合" prop="productIds">
          <el-select
            v-model="queryParams.productIds"
            multiple
            collapse-tags
            clearable
            filterable
            placeholder="请选择"
            style="width: 240px; margin-right: 20px"
          >
            <el-option
              v-for="(item, index) in upChannelOptionList"
              :key="index"
              :label="item.productName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="屏蔽号段" prop="shieldNum">
          <el-input
            style="width: 240px; margin-right: 20px"
            v-model="queryParams.shieldNum"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              plain
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="handelDialog('添加', null)"
              >添加配置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
  
      <div class="table-box">
        <el-row :gutter="10" class="mb8">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="handleQuery"
            :columns="columns"
          ></right-toolbar>
        </el-row>
        <el-table
          v-sticky-header
          ref="table"
          v-loading="loading"
          :data="dataList"
          :span-method="objectSpanMethod"
          border
        >
          <template v-for="(item,index) in columns.slice(0, columns.length - 1)">
            <el-table-column
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="getColumnWidth(index)"
              align="center"
              :fixed="item.fixed"
              :sortable="item.sortable ? item.sortable : false"
              :show-overflow-tooltip="item.showTooltip"
              v-if="item.visible"
            >
              <template slot-scope="scope">
                  <!-- 状态 -->
                  <template v-if="item.prop === 'isShield'">
                    <el-tag 
                      :type="isShieldColor(scope.row[item.prop])" 
                      >
                      {{ ArrayFormatObj(isShieldOption)[scope.row[item.prop]]}}
                    </el-tag>
                  </template>
                  <!-- 使用类型单独处理 -->
                  <template v-else-if="item.prop === 'useType'">
                    <el-tag :type="useTypeColor(scope.row[item.prop])"> {{ ArrayFormatObj(useTypeOption)[scope.row[item.prop]]}}</el-tag>
                  </template>
                  <span v-else>{{scope.row[item.prop]}}</span>
              </template>
            </el-table-column>
          </template>
          <el-table-column
            fixed="right"
            :prop="columns[columns.length - 1].prop"
            :label="columns[columns.length - 1].label"
            align="center"
            :width="getColumnWidth(columns.length - 1)"
            v-if="columns[columns.length - 1].visible"
          >
            <template slot-scope="scope">
              <el-popconfirm
                title="确定要删除渠道号段配置吗？"
                @cancel="hanCancelDel"
                @confirm="handelDel(scope.row)"
                v-if="scope.row['child_isDel']"
              >
                <el-button
                  slot="reference"
                  type="text"
                  ><span style="color: #ff116e">删除</span></el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 使用分页插件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page-sizes="[10, 50, 100, 200, 500]"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <ShieldNumAdd ref="shieldNumAddref" @refresh="getList"></ShieldNumAdd>
    </div>
  </template>
  
  <script>
  import tableStickyMixins from "@/mixins/tableStickyMixins";
  import { mapGetters } from "vuex";
  import {
    shieldNumDel
  } from "@/api/shieldNum/globalConfig";
  import {
    queryShieldUpConfigByPage
  } from "@/api/shieldNum/upConfig";
  import ShieldNumAdd from '@/views/shieldNum/shieldNumAdd.vue'
  import { getUpChannelList } from "@/api/business/channelManagement";
  export default {
    // 定义名字用于标识该组件是否被keep-alive缓存
    name: "UpConfig",
    components:{
      ShieldNumAdd
    },
    data() {
      return {
        // 数据列表
        dataList: [],
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageIndex: 1,
          pageSize: 10,
        },
        loading: false,
        // 表格列信息
        columns: [
        {label: `产品名称`,prop: "productName",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: 'left',showTooltip: true,},
        {label: `状态`,prop: "isShield",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: 'left',showTooltip: true,},
        {label: `使用类型`,prop: "useType",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: 'left',showTooltip: true,},
        {label: `屏蔽号段`,prop: "child_shieldNum",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `操作`,prop: "operation",visible: true,pcWidth: 80,mobileWidth: 80,fixed: "right",showTooltip: true},
        ],
        // 显示搜索栏
        showSearch: true,
        // 状态筛选项
        isShieldOption:[
          { label: "关闭", value: 0 },
          { label: "开启", value: 1 },
        ],
        useTypeOption:[
          { label: "全局配置", value: 0 },
          { label: "独立配置", value: 1 },
        ],
        // 上游渠道筛选项
        upChannelOptionList: [],
        
      };
    },
    mixins: [tableStickyMixins],
    watch: {
      columns: {
        handler() {
          this.updateTableHeight();
        },
        deep: true,
      },
    },
    created() {
      this.getList();
      this.getChannelList();
    },
    computed: {
      ...mapGetters(["sidebar", "device"]),
      // 计算当前列元素在所处环境的宽度
      getColumnWidth() {
        return (index) => {
          return this.isMobile
            ? this.columns[index].mobileWidth
            : this?.sidebar?.opened
            ? this.columns[index].pcWidth - this.slightWidth
            : this.columns[index].pcWidth + 17;
        };
      },
      // 将数组转换为对象形式
      ArrayFormatObj:()=>{
         return (arr)=>{
           return arr.reduce((pre, cur)=>{
             pre[cur.value] = cur.label;
             return pre;
           },{})
         }
      },
      // 状态标签颜色处理
      isShieldColor:()=>{
        return (state)=>{
           switch(state){
             case 0:
                return 'info';
             case 1:
                return 'success';
             default:
                return 'warning';
           }
        }
      },
       // 使用类型值
       useTypeColor(){
         return (type)=>{
            switch (type) {
             case 0:
               return 'warning';
             case 1:
               return 'success';
             default:
               return 'info';
           }
         }
       },
    },
    methods: {
      // 获取渠道筛选项列表
      getChannelList() {
        // 获取上游渠道列表
        getUpChannelList().then((res) => {
          this.upChannelOptionList = res.data;
        });
      },
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 过滤隐藏项合并父级列,排除操作项
      if (!this.columns.filter(pre=>pre?.visible)[columnIndex].prop.includes('child_') && !this.columns.filter(pre=>pre?.visible)[columnIndex].prop.includes('operation')) {
          if (row?.childNum) {
            return {
              rowspan: row?.childNum,
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
      } 
     },
      /** 搜索按钮操作 */
      handleQuery() {
        this.$set(this.queryParams, "pageIndex", 1);
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        // 完全重置到初始状态
        this.$set(this, "queryParams", {
          pageIndex: 1,
          pageSize: 10,
        });
        this.getList();
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        queryShieldUpConfigByPage(this.queryParams).then((response) => {
          let newArr = response?.data?.list?.reduce((arr,pre)=>{
            if(pre?.shieldList?.length){
              // 子项数量
              let childNum = pre?.shieldList?.length
              arr.push(...pre.shieldList.map((item,index)=>{
                // 如果为初始项设置子项数量
                if(index === 0){
                    return  {
                      ...pre,
                      ...this.prefixKeys(item,'child_'),
                      childNum
                    }
                }
                return {
                  ...pre,
                  ...this.prefixKeys(item,'child_')
                }
              }
            ))
            }else{
              arr.push(pre)
            }
            return arr
          },[])
          this.$set(this,'dataList',newArr)
          console.log(this.dataList);

          this.total = response?.data?.total;
          this.loading = false;
        }).catch((err) => {
          setTimeout(() => {// 延迟2s后自动取消加载状态
            this.loading = false;
          }, 2000);
        })
      },
      // 重置属性转化为新对象
       prefixKeys(obj, prefix) {
            return Object.keys(obj).reduce((acc, key) => {
              acc[prefix + key] = obj[key];
              return acc;
            }, {});
       },
      // 修改表格高度触发回调
      updateTableHeight() {
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
      },
      // 处理对话框
      handelDialog(title, row = null) {
        this.$refs.shieldNumAddref.showDilog('添加渠道配置')
      },
      // 取消删除
      hanCancelDel() {
        this.$message({
          type: "info",
          message: "已取消删除操作",
        });
      },
      // 删除列表项
      handelDel(row) {
        shieldNumDel({
          id: row?.child_id,
          configType: 1,
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          }
        });
      },
    },
  };
  </script>
  
  <style scoped lang="scss">
  .title {
    font-size: 20px;
    color: #333333;
    font-weight: 500;
  }
  .search-box {
    margin: 0 0 20px;
    padding: 20px 20px 0;
    background: #fff;
    align-items: flex-start;
    border-radius: 6px;
  }
  .search-area {
    position: absolute;
    right: 20px;
  }
  .el-form-item__content {
    flex: 1;
    line-height: 40px;
    position: relative;
    font-size: 14px;
    min-width: 0;
  }
  ::v-deep .el-dialog__body {
    border-top: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
  }
  .el-table {
    // 滚动条加粗
    --scrollbar-height: 9px;
  }
  </style>
  